package priv.happy.mealpickpro.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
public class ImageController {

    // 用于前端获取图片资源
    @GetMapping("/img/{folder}/{imgName:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String folder, @PathVariable String imgName) {
        // 获取 JAR 文件的同级目录
        String userDir = System.getProperty("user.dir");
        // 构建文件路径
        File file = new File(userDir, "img/" + folder + "/" + imgName);

        // 确保文件存在且可读
        if (file.exists() && file.canRead()) {
            // 使用 FileSystemResource 读取文件
            Resource resource = new FileSystemResource(file);

            // 设置响应头信息
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(getMediaTypeForFileName(file.getName()))  // 动态设置内容类型
                    .body(resource);
        } else {
            // 如果找不到文件，则返回404
            return ResponseEntity.notFound().build();
        }
    }

    private MediaType getMediaTypeForFileName(String fileName) {
        // 根据文件名后缀动态设置MIME类型
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        switch (extension) {
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG;
            case "png":
                return MediaType.IMAGE_PNG;
            case "gif":
                return MediaType.IMAGE_GIF;
            default:
                return MediaType.APPLICATION_OCTET_STREAM;  // 默认为二进制流
        }
    }
}